#include "main.h"


bool MakeSocketNonBlocking(INT32 iSock)
{
    INT32 curFlags = fcntl(iSock, F_GETFL, 0);
    return fcntl(iSock, F_SETFL, curFlags|O_NONBLOCK) >= 0;
}

INT32 SocketReuseAddr(INT32 i_sock_fd, bool b_reuse)
{
    int mode = b_reuse?1:0;
    if( i_sock_fd != -1 ) {
        return setsockopt(i_sock_fd,SOL_SOCKET,SO_REUSEADDR,(void *)&mode,sizeof(int));
    }
    return -1;
}

INT32 sys_time_getms_r(struct timeval &st_init_time, struct timeval &st_now_time, INT64 *pll_sys_ms_time)
{
    INT64 temp = 0;

    gettimeofday(&st_now_time, NULL);

    temp = (INT64)(st_now_time.tv_sec) * (INT64)1000 + (INT64)(st_now_time.tv_usec) / (INT64)1000 - (INT64)st_init_time.tv_sec * (INT64)1000 - (INT64)st_init_time.tv_usec / (INT64)1000;
    *pll_sys_ms_time = temp;

    return 0;
}

INT32 ms_msleep(INT32 i_sleep_ms_time)
{
    INT32 i_ret = 0;
    struct timeval st_tv;
    st_tv.tv_sec  = i_sleep_ms_time / 1000;
    st_tv.tv_usec = (i_sleep_ms_time % 1000) * 1000;

    for (;;) {
        i_ret = select(0, NULL, NULL, NULL, &st_tv);

        if (i_ret == 0) {
            break;
        } else {
            INT32 i_err = errno;
            if ( i_err != EINTR ) {
                printf("err=%s\r\n", strerror(i_err));
                break;
            }
        }
    }

    return i_ret;
}

int main ()
{
    if (0) {
        tcp_send_test();
    } else {
        udp_send_test();
    }

    return 0;
}

